package com.pet_service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet_service.entity.Role;
import com.pet_service.mapper.RoleMapper;
import com.pet_service.mapper.RolePermissionMapper;
import com.pet_service.result.Result;
import com.pet_service.service.RoleService;
import com.pet_service.vo.GrantPermissionBean;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 邹全伸
* @description 针对表【role(角色表)】的数据库操作Service实现
* @createDate 2025-09-20 09:18:18
*/
@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Role> getRoleListByUserId(Integer userId) {
        return roleMapper.selectRoleByUserId(userId);
    }

    @Transactional
    @Override
    public Result removeByRoleIdList(List<Integer> ids) {
        try{
            // 参数校验
            if (ids == null || ids.isEmpty()) {
                return Result.ok("无需删除");
            }
            // 先删除角色权限中间表的数据
            rolePermissionMapper.deleteByRoleIdList(ids);
            // 再删除角色表的数据
            roleMapper.deleteByRoleIdList(ids);
            return Result.ok("删除成功！");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("删除失败！");
        }
    }

    @Transactional
    @Override
    public Result grantPermissionToRole(GrantPermissionBean grantPermissionBean) {
        try{
            log.info("授予权限={}",grantPermissionBean);
            //先删除这个角色拥有的权限
            rolePermissionMapper.deleteByRoleId(grantPermissionBean.getRoleId());
            //再重新给这个角色授予权限
            rolePermissionMapper.insertRolePermission(
                    grantPermissionBean.getRoleId(),grantPermissionBean.getCheckedPermissionIdList());
            return Result.ok("授予权限成功");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("授予权限失败");
        }
    }
}




